package manuscript.mathildemortality;

import repicea.stats.data.DataSet;
import repicea.stats.model.glm.GeneralizedLinearModel;
import repicea.stats.model.glm.LinkFunction.Type;
import repicea.stats.model.glm.copula.CopulaExpression;
import repicea.stats.model.glm.copula.CopulaLibrary;
import repicea.stats.model.glm.copula.FGMCopulaGLModel;
import repicea.util.ObjectUtility;

public class CopulaImplementationWithMortality {

	
	private GeneralizedLinearModel glm;
	private FGMCopulaGLModel copulaSimpleModel;
//	private FGMCopulaGLModel copulaDistanceModel;
	
	
	protected CopulaImplementationWithMortality(String modelDefinition) {
		String path = ObjectUtility.getPackagePath(getClass());
		String filename = path + "dataCopula.csv";
		DataSet dataSet = new DataSet(filename);
		
		glm = new GeneralizedLinearModel(dataSet, Type.Logit, modelDefinition);
		glm.optimize();
//		System.out.println(new HosmerLemeshowTest(glm).toString());
		
		try {

			CopulaExpression simpleCopula = new CopulaLibrary.SimpleCopulaExpression(0.2, "k"); 
			copulaSimpleModel = new FGMCopulaGLModel(glm, simpleCopula);
			copulaSimpleModel.gridSearch(copulaSimpleModel.getParameters().m_iRows - 1, .05d, .10d, .005);
			copulaSimpleModel.optimize();
			
//			CopulaExpression distanceCopula = new CopulaLibrary.DistanceLinkFunctionCopulaExpression(Type.Log, "IDENT", "X + Y", -.15);		// no intercept in the linear expression
//			distanceCopula.setBounds(0, new ParameterBound(null, 0d));
//			copulaDistanceModel = new FGMCopulaGLModel(glm, distanceCopula);
////			copulaDistanceModel.setConvergenceCriterion(1E-3);
//			copulaDistanceModel.gridSearch(copulaDistanceModel.getParameters().m_iRows - 1, -.25d, -.15d, .01);
//			copulaDistanceModel.optimize();

			glm.getSummary();
			copulaSimpleModel.getSummary();
//			copulaDistanceModel.getSummary();
//			System.out.println(new HosmerLemeshowTest(copulaDistanceModel).toString());

//			Matrix test = copulaDistanceModel.getLinearPredictions();
//			DataSet dataset = copulaDistanceModel.getDataStructure().getDataSet();
//			Object[] field1 = new Object[test.m_iRows];
//			Object[] field2 = new Object[test.m_iRows];
//			for (int i = 0; i < test.m_iRows; i++) {
//				field1[i] = test.m_afData[i][0];
//				field2[i] = test.m_afData[i][1];
//			}
//			dataset.addField("linPred", field1);
//			dataset.addField("linPredVar", field2);
//			
//			dataset.save(outputFilename);
			
		} catch (Exception e) {
			e.printStackTrace();
		} 
	}
	
	
	@SuppressWarnings("unused")
	public static void main(String args[]) {
		String simpleDefinition = "mort ~ ess + diam0 + logDiam + logDiam*ess + BAL22 + BAL42 + logDeltat";
		CopulaImplementationWithMortality example1 = new CopulaImplementationWithMortality(simpleDefinition);

	}

	

}
